import { getBtnsId } from '@/libs/btnsPermission';
import { mapGetters, mapMutations } from 'vuex';
import SupplyInfo from '@/pages/commodity/components/SupplyInfo';
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/components/skusTable';
import LaunchReasonInput from '@/components/LaunchReasonInput';
import SetReferenceCity from '@/components/common/dialog/setReferenceCity';
import GoodsLinkedDialog from '@/pages/commodity/components/GoodsLinkedDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import FooterFields from '@/pages/commodity/components/FooterFields';
import infoApi from '../api';
import infoUtils from '../utils';
import { getBtnsBar } from '@/utils/getBtnsRender';
import { getListByReturnMapKey, getSupplyRelativeInfo, getCanOpeState } from '@/utils/getUtils';
import { generateUuid } from '@/utils/bizUtils';
import infoColumns from '../constants/moreSupplyInfoColumns';
import { MAX_EDIT_LIMITS } from '../constants/const';
import { ADD_MULTI_SUPPLY_AMOUNT } from '@/constants/exportAmountLimit';
import { ReferenceCity } from '../class/ReferenceCity';
import { PurchaseTable } from '../class/PurchaseTable';
import { getSupplyCityByAreaCodesService } from '@/api/commodity/common';
export default {
  components: {
    SupplyInfo,
    BtnRender,
    SkusTable,
    LaunchReasonInput,
    SetReferenceCity,
    GoodsLinkedDialog,
    SeniorLinkedDialog,
    FooterFields
  },
  data () {
    return {
      canOpeState: true, // 页面可操作状态
      recordNo: '', // 单据号
      supplyInfo: { // 供应商信息
        supplierCode: '', // 供应商编码
        supplierName: '', // 供应商名称
        supMainCategoryId: '', // 供应商主营品类id
        supMainCategoryName: '', // 供应商主营品类name
        supManagerHrAreaName: '', // 供应商管理区域
        freightPayer: '' // 运费承担方
      },
      taxRateInvoiceInfo: {}, // 税率相关信息
      launchReason: '', // 发起原因
      btnLoading: { // 按钮loading
        infoExport: false, // 导出（多供信息）
        purchaseExport: false, // 导出（多供进价）
        submit: false, // 提交
      },
      infoTable: { // 多供信息表格
        list: [],
        columns: [],
        loading: false
      },
      PurchaseTable: new PurchaseTable(),
      purchaseType: '1', // 供货价格方式，默认为：1-统一进价
      ReferenceCity: new ReferenceCity({ columns: [
        { title: '销售城市', key: 'saleCityName' },
        { title: '区域', key: 'saleAreaName' },
        { title: '参照城市', key: 'templateCityName' },
        { title: '进价比例', key: 'buyPriceRatio' },
        { title: '成本价比例', key: 'costPriceRatio' }
      ] }), // 参照城市类
      supplyAreaParams: [], // 提交入参supplyAreaParams（之一）
      commitUuid: '', // 提交所需唯一标识
      goodsLinked: {
        visible: false,
        queryUrl: '/sysback/multiSupplyInfo/getSkuInfo',
        extraForms: {
          formItemList: [{ label: '供应商编码', prop: 'searchSupplyUuid', type: 'input' }],
          formData: { searchSupplyUuid: '' }
        }
      },
      seniorLinked: { // 高级关联
        visible: false,
        columns: [{
          label: 'SKU编码',
          prop: 'skuNo',
          type: 'textarea'
        }],
        dataSource: [{ skuNo: '' }]
      },
      footerFields: {} // 表尾字段
    }
  },
  mounted () {
    this.setCanOpeState()
    this.loadInitDataInMounted();
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  methods: {
    ...mapMutations('commonComps/setReferenceCity', [
      'SET_TABLE_DATA',
      'SET_REFERENCE_CITIES',
      'SET_PURCHASE_PRICETYPE',
      'DESTORY_STATE'
    ]),
    // 设置页面是否可操作状态值
    async setCanOpeState () {
      this.canOpeState = await getCanOpeState(this.$route.name)
    },
    // 在mounted时期加载初始数据
    loadInitDataInMounted () {
      this.commitUuid = generateUuid();
      this.setColumnsByCanEditLimits();
      if (this.isRecordEdit()) {
        this.setInfoDataByRecordNo();
      }
    },
    // 多供信息按钮操作栏渲染
    renderBtnsBarByInfo (h) {
      return getBtnsBar(h, this.getPrerenderBarListByTableType('info'), this.showBtn);
    },
    // 多供进价按钮操作栏渲染
    renderBtnsBarByPurchase (h) {
      return getBtnsBar(h, this.getPrerenderBarListByTableType('purchase'), this.showBtn);
    },
    // 是单据修改页
    isRecordEdit () {
      if (this.$route.query.recordNo) { return true; }
      return false;
    },
    // 是统一进价
    isUnifiedPurchase () { return this.purchaseType === '1'; },
    // 是区域进价
    isAreaPurchase () { return this.purchaseType === '2'; },
    // 有销售区域不一致
    hasInconsistentSaleAreas () {
      // 点击设置时判断 必须关联商品且关联的商品销售区域必须一致，否则不能进行设置。
      const saleAreaShortNamesList = new Set();
      this.PurchaseTable.unifiedList.forEach(item => { // unifiedList-当前供价表格初始关联数据集合
        saleAreaShortNamesList.add(item.saleAreaShortNames);
      });
      if (saleAreaShortNamesList.size > 1) { return this.$message.warning('商品销售区域必须一致'); }
    },
    // 没有选择供应商
    hasNotChooseSupply () {
      if (!this.supplyInfo.supplierCode) {
        return this.$message.warning('请先选择供应商');
      }
    },
    // 没有关联商品
    hasNotLinkGoods () {
      if (this.PurchaseTable.isNull()) {
        return this.$message.warning('请先关联商品');
      }
    },
    // 没有设置参照城市
    hasNotSetReferCities () {
      if (this.ReferenceCity.isNull()) {
        return this.$message.warning('请先设置参照城市关系');
      }
    },
    /**
     * 提交总量超出最大提交限制限制警告(点击参照城市设置弹框确定按钮时判断)
     * @param {* 当前参照城市集合} cities Array
     */
    hasExcceedSubmitLimitsBySetCities (cities) {
      const citiesNum = cities?.length || 0;
      const tableDataNum = this.PurchaseTable.getSize();
      const multipleNum = citiesNum * tableDataNum;
      if (this.isAreaPurchase() && multipleNum > ADD_MULTI_SUPPLY_AMOUNT) {
        return this.$message.warning(
          `参照城市设置完后导致商品行数超过${ADD_MULTI_SUPPLY_AMOUNT}行，请重新调整商品后设置`
        );
      }
    },
    // 提交多供进价总条数超出提交限制数量限制警告
    hasExcceedSubmitLimitsByEnding () {
      if (this.PurchaseTable.getSize() > ADD_MULTI_SUPPLY_AMOUNT) {
        return this.$message.warning(
          `当前关联商品行数超过${ADD_MULTI_SUPPLY_AMOUNT}行，请重新调整商品后设置`
        );
      }
    },
    // 关联数量超出提交限制数量限制警告
    hasExcceedSubmitLimitsByGoodsLinked () {
      if (this.PurchaseTable.getSize('unified') > ADD_MULTI_SUPPLY_AMOUNT) {
        return this.$message.warning(
          `当前关联商品行数超过${ADD_MULTI_SUPPLY_AMOUNT}行，请重新调整商品后设置`
        );
      }
    },
    // 供货信息或多供进价表格有异常信息提示列
    hasWarnMsgs () {
      const hasNullInfo = this.infoTable.list.some(item => item[infoUtils.getErrMsgColumnInfo().key]);
      const hasNullPrice = this.PurchaseTable.list.some(item => item[infoUtils.getErrMsgColumnInfo().key]);
      return hasNullInfo || hasNullPrice;
    },
    // 设置页面信息 by 单据号（修改页面方法）
    async setInfoDataByRecordNo () {
      this.recordNo = this.$route.query.recordNo;
      const retData = await infoApi.getRecordInfo(this.recordNo);
      if (!retData) { return false; }
      const {
        supplyPriceType,
        supplySkuRels,
        supplyAreaPriceParams,
        launchReason,
        supplyAreaParams
      } = retData.productRel;
      const [supplyData] = await infoApi.getSupplyInfo(retData.productRel.supplyUuid);
      this.setSupplyRelativeInfo(getSupplyRelativeInfo(supplyData));
      this.footerFields = retData.recordDetail; // 表尾字段
      this.purchaseType = supplyPriceType; // 供货价格方式
      this.launchReason = launchReason; // 发起原因
      this.supplyAreaParams = supplyAreaParams;
      this.setEchoDataByReferCity(retData.productRel); //
      this.infoTable.list = supplySkuRels; // 供货信息表格
      this.setInitUnifiedByEdit(supplyAreaPriceParams); // 供货价格表格
      this.countPurchaseTable(); // 重新计算表格数据
      this.setColumnsByCanEditLimits({ setType: 'tableList' }); // 重新加载一次表格表列
    },
    // 设置参照城市回显数据（修改页面方法）
    setEchoDataByReferCity ({ defaultTemplateCityName, defaultTemplateCityUuid }) {
      const tableData = this.supplyAreaParams.map(item => ({
        ...item,
        saleCityNo: item.saleCityUuid,
        saleProvinceNo: item.saleProvinceUuid
      }));
      this.ReferenceCity.setList(this.supplyAreaParams); // 参照城市展示表格
      this.ReferenceCity.setDefaultCity({
        templateCityUuid: defaultTemplateCityUuid,
        templateCityName: defaultTemplateCityName
      }); // 默认参照城市
      this.SET_TABLE_DATA(tableData); // 参照城市表格
    },
    /**
     * 初始化价格数据 根据 计量（单计量、多计量）（修改页面方法）
     * @param {* 修改页面单据所获取的价格数据出参} supplyAreaPriceParams Array
     * @param {* 要进行初始化表格数据的方法} initMethod Function
     * @returns Function
     */
    initSupplyAreaPriceByUintType (supplyAreaPriceParams) {
      return initMethod => {
        const initCityList = infoUtils.getUniqLisByDimension(supplyAreaPriceParams);
        const initPriceList = initMethod(
          initCityList,
          this.taxRateInvoiceInfo,
          this.purchaseType
        );
        this.PurchaseTable.initAll(
          supplyAreaPriceParams.map(item => ({ ...item, ...this.taxRateInvoiceInfo })),
          initPriceList
        );
      }
    },
    // 设置供应商相关信息
    setSupplyRelativeInfo ({ supplyInfo, taxRateInfo }) {
      this.supplyInfo = supplyInfo;
      this.taxRateInvoiceInfo = taxRateInfo;
    },
    /**
     * 设置供货信息和多供进价表格columns
     * @param {* 要进行设置的方法类别} setType String
     * @param {* 不进行警告提示} hasNoWarnning Boolean 默认为非，取反即默认提示
     */
    setColumnsByCanEditLimits (data = {}) {
      const { setType = 'goodsLinked', hasWarnning = true } = data;
      const runMethods = {
        goodsLinked: this.setColumnsByGoodsLinked,
        tableList: this.setColumnsByTableList
      }
      const defaultFn = () => {};
      const method = runMethods[setType] || defaultFn;
      method(hasWarnning);
    },
    // 根据关联商品数量进行表格表列的设置
    setColumnsByGoodsLinked (hasWarnning) {
      const hasGoodsExceedLimits = this.$refs.goodsLinked.LinkGoods.getSize() > MAX_EDIT_LIMITS;
      if (hasGoodsExceedLimits) {
        if (hasWarnning) {
          this.$message.warning(`关联商品超出最大可编辑数量（${MAX_EDIT_LIMITS}条），请导出表格进行编辑`);
        }
        this.infoTable.columns = infoColumns.viewMoreSupplyInfoColumns;
        this.setPurchaseColumnsByEditState(false);
      } else {
        this.infoTable.columns = infoColumns.moreSupplyInfoColumns;
        this.setPurchaseColumnsByEditState(true);
      }
    },
    // 根据当前表格数据量进行表格表列的设置
    setColumnsByTableList () {
      const hasInfoExceedLimits = this.infoTable.list.length > MAX_EDIT_LIMITS; // 供货信息超过不可编辑数量
      const hasPriceExceedLimits = this.PurchaseTable.getSize() > MAX_EDIT_LIMITS; // 多供进价超过不可编辑数量
      if (hasInfoExceedLimits || hasPriceExceedLimits) {
        this.$message.warning(`多供信息或多供进价超出最大可编辑数量（${MAX_EDIT_LIMITS}条），请导出表格进行编辑`);
      }
      if (hasInfoExceedLimits) { // 供货信息设置不可编辑表列
        this.infoTable.columns = infoColumns.viewMoreSupplyInfoColumns;
      }
      if (hasPriceExceedLimits) { // 多供进价设置不可编辑表列
        this.setPurchaseColumnsByEditState(false);
      }
    },
    /**
     * 设置多供进价-表格columns
     * @param {* 表格columns相关数据} columns Object
     * @param {* 能否编辑} canEdit Boolean
     * editUnifiedColumns - 统一进价表格columns（可编辑）
     * cannotEditUnifiedColumns - 统一进价表格columns（不可编辑）
     * editAreaColumns - 区域进价表格columns（可编辑）
     * cannotEditAreaColumns - 区域进价表格columns（不可编辑
     * @returns Function 可以根据编辑状态进行设置的表格方法
     */
    setPurchaseColumns (columns) {
      return canEdit => {
        const unifiedColumns = canEdit
          ? _.cloneDeep(columns.editUnifiedColumns)
          : _.cloneDeep(columns.cannotEditUnifiedColumns);
        const areaColumns = canEdit
          ? _.cloneDeep(columns.editAreaColumns)
          : _.cloneDeep(columns.cannotEditAreaColumns);
        if (this.isUnifiedPurchase()) { // 统一进价
          this.PurchaseTable.setColumns(unifiedColumns);
        }
        if (this.isAreaPurchase()) { // 区域进价
          this.PurchaseTable.setColumns(areaColumns);
        }
      }
    },
    // 重置相关数据 by 重新选择供应商
    resetRelativeDataByRechooseSupply (supplierCode) {
      if (this.supplyInfo.supplierCode !== supplierCode) {
        this.resetTableData();
        this.resetLinkGoods();
        this.resetReferCityData();
        this.setColumnsByCanEditLimits();
      }
    },
    // 重置参照城市相关数据
    resetReferCityData () {
      this.ReferenceCity.clearAll();
      this.DESTORY_STATE(); // 清空参照城市弹框所有状态
    },
    // 重置表格数据
    resetTableData () {
      this.infoTable.list = []; // 供货信息表格数据
      this.PurchaseTable.clearAll();
    },
    // 重置关联商品数据
    resetLinkGoods () {
      this.$refs.goodsLinked.LinkGoods.clear(); // 关联商品类-清空方法
    },
    // 高级关联
    handleSeniorLinked () {
      if (this.hasNotChooseSupply()) { return false; }
      sessionStorage.setItem('buttonId', getBtnsId('高级关联'));
      this.seniorLinked.visible = true;
    },
    // 关联商品
    handleGoodsLinked () {
      if (this.hasNotChooseSupply()) { return false; }
      sessionStorage.setItem('buttonId', getBtnsId('关联商品'));
      this.goodsLinked.visible = true;
    },
    // 提交
    handleSubmit () {
      if (this.hasNotChooseSupply()) { return false; }
      if (this.hasNotLinkGoods()) { return false; }
      if (this.hasNotSetReferCities()) { return false; }
      if (this.hasExcceedSubmitLimitsByEnding()) { return false; }
      if (this.hasWarnMsgs()) {
        this.confirmBySubmit();
      } else {
        this.submitMoreSupplyData(); // 提交多供信息和进价数据
      }
    },
    // 模板导出（多供信息）
    handleExportByInfo () {
      if (this.hasNotChooseSupply()) { return false; }
      if (this.hasNotLinkGoods()) { return false; }
      infoApi.exportInfoData({
        skuNos: getListByReturnMapKey(this.infoTable.list, 'skuNo'),
        supplyUuid: this.supplyInfo.supplierCode,
        supplyName: this.supplyInfo.supplierName,
        supplySkuRels: this.infoTable.list
      }, () => { this.btnLoading.infoExport = true; },
      () => { this.btnLoading.infoExport = false; }
      );
    },
    // 上传成功回调（多供信息）
    handleUploadSuccessByInfo (res) {
      this.infoTable.loading = false;
      if (res.retStatus !== '1') {
        this.$message.error(res.retMessage || '导入失败');
        return false;
      }
      this.runImportResultsByInfo(res.retData);
    },
    // 模板导出（多供进价）
    handleExportByPurchase () {
      if (this.hasNotChooseSupply()) { return false; }
      if (this.hasNotLinkGoods()) { return false; }
      if (this.hasNotSetReferCities()) { return false; }
      this.exportPurchaseData();
    },
    // 上传成功回调（多供进价）
    handleUploadSuccessByPurchase (res) {
      this.PurchaseTable.stopLoading();
      if (res.retStatus !== '1') {
        this.$message.error(res.retMessage || '导入失败');
        return false;
      }
      this.runImportResultByPrice(res.retData);
    },
    // 切换供货价格方式
    handleSwitchPurchaseStatus (val) {
      if (this.ReferenceCity.isNull()) {
        this.updateCurrentPurchaseList();
        this.setColumnsByCanEditLimits();
        return false;
      }
      this.confirmBySwitchPurchaseType(val);
    },
    // 设置参照城市关系
    handleSetReferCityRelation () {
      if (this.hasNotChooseSupply()) { return false; }
      if (this.hasNotLinkGoods()) { return false; }
      if (this.hasInconsistentSaleAreas()) { return false; }
      if (this.hasExcceedSubmitLimitsByGoodsLinked()) { return false; }
      this.ReferenceCity.openDialog();
    },
    // 供货价格表格row删除
    handleRowDeleteByPurchaseTable ({ row }) {
      this.deleteRowsBySkuNo(row);
      const isGoodsUnderCanEditLimits = this.PurchaseTable.getSize() <= MAX_EDIT_LIMITS;
      if (isGoodsUnderCanEditLimits) { // 当前多供进价表格数量没有超过最大可编辑数量
        this.setColumnsByCanEditLimits({ hasWarnning: false });
      }
    },
    // 按照skuNo删除表格行数据
    deleteRowsBySkuNo (row) {
      const filterMethod = list => list.filter(item => item.skuNo !== row.skuNo);
      this.infoTable.list = filterMethod(this.infoTable.list); // 供货信息表格
      this.PurchaseTable.setList(filterMethod(this.PurchaseTable.list)); // 供价表格
      this.PurchaseTable.setUnified(filterMethod(this.PurchaseTable.unifiedList)); // 统一供价表格
      this.PurchaseTable.setArea(this.PurchaseTable.areaList); // 区域供价表格
      this.$refs.goodsLinked.LinkGoods.delete(row); // 关联表格
    },
    // 获取可设置参照关系的城市列表
    async getCityListByCanSetReferRelation () {
      const data = { areaCode: this.PurchaseTable.unifiedList[0]?.saleAreaNos?.join(',') }
      const res = await getSupplyCityByAreaCodesService(data);
      if (!res?.retData) { return false; }
      // 设置参照城市二级弹框表格数据
      this.SET_TABLE_DATA(infoUtils.getInitReferCityTableDataBySetDialog(res.retData));
      // 设置参照城市二级弹框表格列-参照城市下拉集合
      this.SET_REFERENCE_CITIES(infoUtils.getBatchCityOptions(res.retData));
      // 设置参照城市二级弹框供货价格方式
      this.SET_PURCHASE_PRICETYPE(this.purchaseType);
      return true;
    },
    // 获取设置后的参照城市列表
    getSetCityListByReferRelation ({ tableData, defaultCity }) {
      if (!tableData) { return false }
      this.ReferenceCity.setDefaultCity(defaultCity);
      // 获取参数处理后的已设置参照城市列表
      this.supplyAreaParams = infoUtils.getCitiesBySetReferRelation(
        tableData, this.supplyInfo.supplierCode
      );
      // 获取参照城市展示表格数据(区域价格表格数据只取自己参照自己的数据，即销售城市和参照城市相同的数据)
      const uniqReferCities = this.supplyAreaParams.filter(
        item => item.saleCityNo === item.templateCityUuid
      );
      if (this.hasExcceedSubmitLimitsBySetCities(uniqReferCities)) { return false; }
      this.ReferenceCity.setList(uniqReferCities);
      this.PurchaseTable.setArea(infoUtils.getAreaTableDataBySetReferCity(
        this.PurchaseTable.unifiedList,
        this.ReferenceCity.list
      ));
      this.PurchaseTable.setListByType(this.isAreaPurchase());
      this.setColumnsByCanEditLimits({ setType: 'tableList' });
    },
    // 获取表格数据 by 关联商品
    getTableDataByGoodsLinked (linkedGoods) {
      this.initAllTableData(linkedGoods);
    },
    // 获取供货信息操作栏按钮集合
    getInfoBars () {
      const btnList = [
        {
          label: '高级关联',
          method: this.handleSeniorLinked,
          icon: 'el-icon-link',
          size: 'large',
          hasAuth: true
        },
        {
          label: '关联商品',
          method: this.handleGoodsLinked,
          size: 'large',
          hasAuth: true
        },
        {
          label: '模板导入',
          action: 'sysback/supplyskurel/importTemplateForCreate',
          methods: { handleUploadSuccess: this.handleUploadSuccessByInfo },
          isImport: true,
          loadingFn: state => { this.infoTable.loading = state },
          data: {
            supplyUuid: this.supplyInfo?.supplierCode, // 供应商编码
            manySupply: '1' // 是否多供，1为多供
          }
        },
        {
          label: '模板导出',
          method: this.handleExportByInfo,
          loading: this.btnLoading.infoExport,
          size: 'large'
        },
        {
          label: '提交',
          method: this.handleSubmit,
          loading: this.btnLoading.submit,
          size: 'large',
          canOpeState: this.canOpeState
        }
      ];
      if (this.isRecordEdit()) {
        btnList.push({
          label: '返回',
          size: 'large',
          method: () => { this.$router.push({ name: 'chageFromManageList' }) }
        })
      }
      return btnList.filter(item => item.canOpeState != false);
    },
    // 获取多供进价操作栏按钮集合
    getPurchaseBars (importUrl) {
      const loadingFn = this.PurchaseTable.changeLoading.bind(this.PurchaseTable);
      return [
        {
          label: '模板导入',
          action: importUrl,
          methods: { handleUploadSuccess: this.handleUploadSuccessByPurchase },
          isImport: true,
          loadingFn: state => { loadingFn(state) },
          data: {
            supplyUuid: this.supplyInfo?.supplierCode, // 供应商编码
            purchasePriceType: this.purchaseType, // 供货价格方式
            manySupply: '1' // 是否多供，1为多供
          }
        },
        {
          label: '模板导出',
          method: this.handleExportByPurchase,
          loading: this.btnLoading.purchaseExport,
          size: 'large'
        },
      ]
    },
    /**
     * 导出多供进价表格数据 by 计量（单计量或多计量）
     * @param {* 用来区分单计量还是多计量的，1是单计量，2是多计量} productType String
     * @param {* 模板名称} exceTitle String
     */
    exportPurchaseDataByUnitType () {
      return (productType, exceTitle) => {
        const supplyAreaPriceParams = infoUtils.getSupplyAreaPriceParams({
          purchaseTable: this.PurchaseTable.list,
          purchasePriceType: this.purchaseType,
          supplyInfo: this.supplyInfo,
          defaultReferenceCity: this.ReferenceCity.defaultCity,
          isAreaPurchase: this.isAreaPurchase()
        });
        infoApi.exportPurchaseData(
          {
            productType, // 用来区分单计量还是多计量的，1是单计量，2是多计量
            skuNos: getListByReturnMapKey(this.PurchaseTable.list, 'skuNo'),
            supplyPriceType: this.purchaseType, // 供货价格方式
            supplyAreaParams: this.ReferenceCity.list, // 参照关系列表
            supplyUuid: this.supplyInfo.supplierCode, // 供应商编码
            supplyName: this.supplyInfo.supplierName, // 供应商名称
            supplyAreaPriceParams // 多供进价表格数据
          },
          () => { this.btnLoading.purchaseExport = true; },
          () => { this.btnLoading.purchaseExport = false; },
          exceTitle
        );
      }
    },
    /**
     * 提交供货相关数据 by 计量类型（单计量或多计量）
     * @param {* 供货价格提交校验方法} hasEmptyPrice Function
     * @param {* 计量单位 - 1为多计量，2为单计量} isPurchaseMultiUnit String
     */
    submitMoreSupplyDataByUnitType () {
      return async (hasEmptyPrice, isPurchaseMultiUnit) => {
        const commonParams = {
          supplyInfo: this.supplyInfo,
          defaultReferenceCity: this.ReferenceCity.defaultCity,
          isAreaPurchase: this.isAreaPurchase()
        }
        const supplyAreaPriceParams = infoUtils.getSupplyAreaPriceParams({
          purchaseTable: this.PurchaseTable.list,
          purchasePriceType: this.purchaseType,
          ...commonParams
        });
        const { hasEmptyVal, msg } = hasEmptyPrice(supplyAreaPriceParams);
        if (hasEmptyVal) { return this.$message.warning(msg); }
        const submitParams = infoUtils.getSubmitParamsByMoreSupply({
          supplyAreaPriceParams,
          isPurchaseMultiUnit,
          supplyAreaParams: this.supplyAreaParams,
          infoTable: this.infoTable.list,
          commitUuid: this.commitUuid,
          launchReason: this.launchReason,
          supplyPriceType: this.purchaseType,
          ...commonParams
        });
        const retData = await infoApi.submitMoreSupplyData(
          submitParams,
          () => { this.btnLoading.submit = true; },
          () => { this.btnLoading.submit = false; }
        );
        if (retData) {
          this.runSubmitResults(retData);
        }
      }
    },
    /**
     * 执行提交结果
     * @param {* 错误信息} errInfo Object
     * @param {* 供货信息-错误信息} supplyInfoErrMap Object
     * @param {* 多供进价-错误信息} supplyPriceErrMap Object
     */
    runSubmitResults (errInfo) {
      const errColumn = infoUtils.getErrMsgColumnInfo('禁止提交原因');
      const { supplyInfoErrMap, supplyPriceErrMap } = errInfo;
      if (supplyInfoErrMap || supplyPriceErrMap) {
        this.$message.warning('存在禁止提交原因，无法提交单据');
      }
      if (supplyInfoErrMap) { // 供货信息
        this.infoTable.list = infoUtils.getTableDataByHasErrMsgs(
          this.infoTable.list,
          supplyInfoErrMap
        );
        this.infoTable.columns = [
          errColumn,
          ...this.infoTable.columns.filter(item => item.key !== errColumn.key)
        ];
        return false;
      }
      if (supplyPriceErrMap) { // 多供进价
        this.PurchaseTable.setList(infoUtils.getTableDataByHasErrMsgs(
          this.isAreaPurchase() ? this.PurchaseTable.list : this.PurchaseTable.list.map(item => ({
            ...item,
            templateCityUuid: this.ReferenceCity?.defaultCity?.templateCityUuid
          })),
          supplyPriceErrMap
        ));
        this.PurchaseTable.setColumns([
          errColumn,
          ...this.PurchaseTable.columns.filter(item => item.key !== errColumn.key)
        ]);
        return false;
      }
      this.$message.success('提交成功');
      this.$router.push({ name: 'chageFromManageList' }); // 跳转修改表单页面
    },
    // 执行供货信息导入结果
    runImportResultsByInfo (retData) {
      const errColumn = infoUtils.getErrMsgColumnInfo('导入错误信息');
      const hasErrMsgs = retData.some(item => item.errMsg);
      if (hasErrMsgs) {
        this.$message.warning('供货信息导入存在异常信息');
        this.infoTable.columns = [
          errColumn,
          ...this.infoTable.columns.filter(item => item.key !== errColumn.key)
        ];
      }
      this.infoTable.list = retData;
    },
    // 执行多供进价导入结果
    runImportResultByPrice (retData) {
      const errColumn = infoUtils.getErrMsgColumnInfo('导入错误信息');
      const hasErrMsgs = retData.some(item => item.errMsg);
      if (hasErrMsgs) {
        this.$message.warning('多供进价导入存在异常信息');
        this.PurchaseTable.setColumns([
          errColumn,
          ...this.PurchaseTable.columns.filter(item => item.key !== errColumn.key)
        ]);
      }
      this.PurchaseTable.setList(infoUtils.getInitTableDataByPurchaseImport({
        list: retData,
        taxRateInvoiceInfo: this.taxRateInvoiceInfo,
        handleRowChange: this.handleRowChangeByPurchaseTable
      }));
    },
    // 切换供货价格方式警告提示
    confirmBySwitchPurchaseType (val) {
      this.$confirm(
        '切换进价类型后会清空设置好的参照城市以及进价信息，你确定要切换吗',
        '提示',
        { type: 'warning' }
      ).then(() => {
        this.setColumnsByCanEditLimits();
        this.PurchaseTable.resetList(); // 切换重置表格数据
        this.ReferenceCity.clearAll(); // 清空参照
        this.updateCurrentPurchaseList();
      }).catch(() => {
        if (val === '1') { this.purchaseType = '2'; }
        if (val === '2') { this.purchaseType = '1'; }
      });
    },
    // 提交有导入异常信息警告提示
    confirmBySubmit () {
      this.$confirm(
        '存在异常提示，是否仍要提交？',
        '提交异常提示',
        {
          type: 'warning',
          confirmButtonText: '仍要提交',
          cancelButtonText: '查看详情'
        }
      ).then(() => {
        this.submitMoreSupplyData();
      }).catch(() => {})
    },
    // 更新当前表格数据
    updateCurrentPurchaseList () {
      this.PurchaseTable.setList(
        this.PurchaseTable.list.map(item => ({ ...item, purchasePriceType: this.purchaseType }))
      );
    }
  }
}
